package com.atguigu.gulimall.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.atguigu.gulimall.order.vo.alipay.PayAsyncVo;
import com.atguigu.gulimall.order.vo.alipay.PayVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程；；；；；" + Thread.currentThread().getId());
        // 获取之前的请求 解决异步情况下，feign调用请求头丢失问题，每个异步任务里面设置请求头
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1、远程调用所有的地址列表
            //System.out.println("member线程；；；；；"+Thread.currentThread().getId());
            //每一个线程共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);


        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2、远程查询购物车所有选中的购物项
            //System.out.println("cart线程；；；；；"+Thread.currentThread().getId());
            //每一个线程共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItem();
            confirmVo.setItems(items);
            //feign在远程调用之前要构请求，调用很多的拦截器
            //RequestInterceptor interceptor:requestInterceptors
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            //每一个线程共享之前的请求数据   这里查询库存，不需要登录状态，所以不需要带共享数据
            //RequestContextHolder.setRequestAttributes(requestAttributes);
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            // TODO: 2022/3/6 需要启动库存服务， 否则库存查不出
            //远程调用得到所有带有库存信息的数据
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);


        //3.查询用户积分,保存
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //4、其他数据自动计算（OrderConfirmVo中的get方法）

        //5、 TODO: 2022/3/5  防止重复提交令牌
        String token = IdUtil.fastSimpleUUID();
        //服务器和页面各带一份
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);


        try {
            //完成两个异步调用再返回
            CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return confirmVo;

    }

    //同一个对象内事物的方法互调默认失效，原因是跳过了代理对象
    //事物使用代理对象控制的
    @Transactional(timeout = 30) //a事物
    public void a() {
        /**
         * 有坑的地方：这种情况 b,c 做任何设置都没有用，都是和a公用一个事物
         */
        //b(); 没用  //a事物
        //c(); 没用  //新事物，不回滚
        //用代理对象调用就可以让配置生效
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b(); //生效
        orderService.c();  //生效

        //要想生效  这样就经过了代理对象
        //bOrderService.b();
        //cOrderService.c();
        int i = 10 / 0;
    }

    /**
     * b 会继承a方法的事物，所以配置也是跟着a的配置  a和b共用一个事物
     */
    @Transactional(propagation = Propagation.REQUIRED, timeout = 2)
    public void b() {
    }

    /**
     * 这是个新事物，a不会影响它的配置
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 20)
    public void c() {

    }

    //本地事物，在分布式系统中，只能控制自己的回滚，控制不了其他服务的回滚
    //分布式事物：网络问题+分布式机器
    //(isolation = Isolation.REPEATABLE_READ)
    //(propagation = Propagation.REQUIRES_NEW)
    //@GlobalTransactional
    //高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();

        //从拦截器里面获取用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);
        //redis中令牌的key
        String redisKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        //1.验证令牌(redis和页面的额令牌一致性)【令牌的对比和删除必须原子性】
        //返回 0和1  0--代表失败  1代表删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        /**
         * 原子验证和删除令牌
         * 1、Long类型  脚本返回0和1
         * 2、redisKey key的集合，这里只有一个key
         * 3、需要对比的数据

         */
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisKey), orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else {
            //1、下单：去创建订单，验令牌，验价格，锁库存
            //创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            //价格差的绝对值小于0.01
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功
                //3、保存订单
                saveOrder(order);
                //4、库存锁定 只要有异常，回滚订单数据
                //订单号，所有的订单项（skuId,skuName,num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> locks = order.getOrderItems().stream().map((item) -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // TODO: 2022/3/9 远程锁库存
                //库存成功了，但是网络原因超时了，订单回滚，库存不回滚
                //为了保证高并发，库存服务自己回滚。可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式  消息
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁成功了
                    response.setOrder(order.getOrder());
                    // TODO: 2022/3/10 远程扣减积分  出现异常
                    //int i = 10 / 0;  //订单回滚，库存不回滚
                    // TODO: 2022/3/18   订单创建成功发送消息给MQ
                    //(String exchange, String routingKey, Object message, MessagePostProcessor messagePostProcessor,
                    //			CorrelationData correlationData
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    //System.out.println(order);
                    return response;
                } else {
                    //锁失败了

                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                    //return response;
                }

            } else {
                response.setCode(2);
                return response;
            }

            //令牌验证成功
        }


        //String redisToken = redisTemplate.opsForValue().get(redisKey);
        //if (orderToken != null&&orderToken.equals(redisToken)) {
        //    //验证通过
        //    redisTemplate.delete(redisKey);
        //}else {
        //    //验证不通过
        //}
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //解锁成功，发送给MQ一个
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                // TODO: 2022/3/18 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                // TODO: 2022/3/18  定期扫描数据库，将失败的额消息再发一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (AmqpException e) {
                // TODO: 2022/3/18 将没发送成功的消息进行重试发送


            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo vo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        /**
         * Bigdecimal默认是四位小数，支付宝无法识别，需要处理 ,保留两位小数，并且向上取值
         */
        BigDecimal num = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        vo.setTotal_amount(num.toString());
        //交易号
        vo.setOut_trade_no(order.getOrderSn());
        //取交易订单项中第一个商品作为标题
        List<OrderItemEntity> entities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = entities.get(0);
        vo.setSubject(orderItemEntity.getSkuName());
        //备注  --这里把销售属性作为备注
        vo.setBody(orderItemEntity.getSkuAttrsVals());
        return vo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            //查出每一个订单对应的订单项，
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            //设置进每一个订单项
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        savePaymentInfo(vo);
        //2、修改订单状态信息
        String trade_status = vo.getTrade_status();
        /**
         * 状态 TRADE_SUCCESS 的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功；
         * 交易状态 TRADE_FINISHED 的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；
         */
        if ("TRADE_SUCCESS".equals(trade_status)|| "TRADE_FINISHED".equals(trade_status)) {
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {

        // TODO: 2022/3/31 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal(""+seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        // TODO: 2022/3/31 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        // TODO: 2022/3/31 获取当前sku的详细信息设置    productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());
        R r = productFeignService.getSpuInfoBySkuId(seckillOrder.getSkuId());
        if (r.getCode()==0){
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {});
            orderItemEntity.setSpuName(data.getSpuName());
            orderItemEntity.setSkuQuantity(seckillOrder.getNum());
            orderItemEntity.setRealAmount(multiply);
        }
        orderItemService.save(orderItemEntity);
    }


    /**
     * 保存交易流水
     */
    private void savePaymentInfo(PayAsyncVo vo) {
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        infoEntity.setCreateTime(vo.getGmt_create());
        infoEntity.setConfirmTime(vo.getGmt_payment());
        infoEntity.setSubject(vo.getSubject());
        OrderEntity order = this.getOrderByOrderSn(infoEntity.getOrderSn());
        infoEntity.setOrderId(order.getId());
        infoEntity.setTotalAmount(new BigDecimal(vo.getTotal_amount()));
        paymentInfoService.save(infoEntity);
    }

    /**
     * 保存订单的所有数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单数据
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        this.save(orderEntity);
        //保存订单项数据
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3、计算价格、积分等相关信息
        computeRrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;

    }


    private void computeRrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //1、订单价格相关
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        //积分、成长值
        BigDecimal gift = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        //订单的总额，叠加每一个订单总额的信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);
        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        //订单状态 0-未删除
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 按照订单号，生成订单
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //会员id
        entity.setMemberId(memberRespVo.getId());
        //获取收货地址信息
        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货信息
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        //设置订单的相关状态信息
        entity.setCreateTime(new Date());
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        return entity;
    }

    /**
     * 构建所有订单项数据
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem != null && currentUserCartItem.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItem.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号 √
        //2、商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setSpuId(data.getId());
        //itemEntity.setSpuPic();  这个spu里面没封装，spu里面图片都是介绍。图片是和sku关联的
        itemEntity.setCategoryId(data.getCatalogId());

        //3、商品的sku信息
        itemEntity.setSkuId(skuId);
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //集合转成;分割的字符串
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【不做】
        //5、积分信息 (默认当做金额)
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额  单价*数量   总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        //进去各种优惠价格
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }
}